package com.decent.ejfadmin.utils;

import com.decent.ejfadmin.common.enums.SupWebErrorCode;
import com.decent.ejfadmin.common.exception.ErrorCodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * describe:图片工具类
 *
 * @author 陈豆豆
 * @date 2019/09/07
 */
@Slf4j
public final class PictureUtil {
    /**
     * 将图片转为二进制
     *
     * @param file 文件
     * @return 二进制数据
     */
    public static byte[] dealLogo(MultipartFile file) {
        byte[] bytes = null;
        try {
            //创建文件输入流
            InputStream inputStream = file.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedImage read = ImageIO.read(inputStream);
            ImageIO.write(read, "png", baos);
            //将目标文件转换成byte数组
            bytes = baos.toByteArray();
        } catch (IOException e) {
            log.warn("图片转换二进制失败{}", e, e);
        }
        if (bytes == null) {
            throw new ErrorCodeException(SupWebErrorCode.SYSTEM_ERROR.getError());
        }
        return bytes;
    }


}